<template>
  <div>
    <!-- 消息推送模板 -->
    <search-form
      :search-config="searchConfig"
      :label-width="150"
      @clear="clearSearch"
      @search="handleSearch"
    />
    <table-box
      ref="newsFeeds"
      :selected-arry.sync="tableSelected"
      :table-config="tableConfig"
      :other-filters="otherFilters"
      :other-raw="otherRaw"
      :off-set="-20"
      show-index
      show-selection
      @btnOperate="btnOperate"
      @selection-change="selectionChangeHandle"
    />
    <div>
      <edit-dialog v-if="showAddPage" ref="editdlg" :visible.sync="showAddPage" :detail-data="activatedData" @success="refreshTable" />
    </div>
  </div>
</template>

<script>
import editDialog from './component/EditDialog.vue'
import { getDictByPatchType } from '@/api/dataDict'
import { changeMessageState } from '@/api/basicData'
export default {
  name: 'NewsFeeds',
  components: { editDialog },
  data() {
    return {
      showAddPage: false,
      activatedData: {},
      surveyStateList: [],
      designScheduleList: [],
      decorationStepsList: [],
      designStateList: [],
      taskStateList: [],
      constScheduleList: [],
      accScheduleList: [],
      reminderModeList: [],
      reminderRoleList: [],
      performTasksList: [],
      currentTimeList: [],
      searchConfig: [
        { label: '消息推送模板名称', prop: 'configName', type: 'text', value: '', placeholder: '' },
        {
          label: '对应流程',
          prop: 'belongProcess',
          type: 'select',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/CORRESPONDING_PROCESS?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        {
          label: '提醒角色',
          prop: 'remindRole',
          type: 'select',
          config: {
            remote: true,
            multiple: true,
            remoteUrl: `/data-dict/api/v2/dictionary/REMIND_ROLE?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        }
      ],
      tableSelected: [],
      otherRaw: {},
      otherFilters: [],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configMessageTemplate/page`,
        hideSearchBar: true,
        // sort: 'seriesCode',
        // order: 'ASC',
        setting: [
          {
            prop: 'configName',
            label: '消息推送模板名称',
            minWidth: '100'
          },
          {
            prop: 'belongProcess',
            label: '对应流程',
            minWidth: '100',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'CORRESPONDING_PROCESS'
            }
          },
          {
            prop: 'fieldName',
            label: '相关字段',
            minWidth: '100'
            // propEnum: {
            //   domainCode: 'marketing',
            //   appCode: 'slm',
            //   dictTypeCode: 'DESIGN_BIZ_TYPE'
            // }
          },
          {
            prop: 'fieldValue',
            label: '相关字段值',
            minWidth: '100',
            render: (creat, row) => {
              if (!row.fieldValue) {
                return
              }
              let list = []
              if (row.belongProcess === 'A') {
                list = this.surveyStateList // 测绘进度
              } else if (row.belongProcess === 'D') {
                list = this.designScheduleList // 图纸设计进度
              } else if (row.belongProcess === 'E') {
                list = this.decorationStepsList // 装修步骤
              } else if (row.belongProcess === 'B') {
                list = this.designStateList // 设计进度--设计流程
              } else if (row.belongProcess === 'C') {
                list = this.taskStateList // 设计任务进度--设计任务
              } else if (row.belongProcess === 'F') {
                list = this.constScheduleList // 门店建设BEFORE_CONST_SCHEDULE
              } else if (row.belongProcess === 'G') {
                list = this.accScheduleList // 资源饰品ACC_SCHEDULE
              }
              const arr = list.filter(item => item.dictCode === row.fieldValue)
              return (<span>{(arr.length && arr[0].dictName) || row.fieldValue}</span>)
            }
          },
          {
            prop: 'remindRole',
            label: '提醒角色',
            minWidth: '100',
            render: (creat, row) => {
              if (!row.remindRole) {
                return
              }
              let list = []
              if (typeof (row.remindRole) === 'string') {
                list = row.remindRole.split(',')
              } else {
                list = row.remindRole
              }
              const arr = []
              this.reminderRoleList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'remindType',
            label: '提醒方式',
            minWidth: '100',
            render: (creat, row) => {
              if (!row.remindType) {
                return
              }
              let list = []
              if (typeof (row.remindType) === 'string') {
                list = row.remindType.split(',')
              } else {
                list = row.remindType
              }
              const arr = []
              this.reminderModeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'executeRule',
            label: '执行规则',
            minWidth: '100',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'EXECUTE_RULE'
            }
          },
          {
            prop: 'cronJobRule',
            label: '执行定时任务规则',
            minWidth: '100',
            render: (creat, row) => {
              if (!row.cronJobRule) {
                return
              }
              const arr1 = this.performTasksList.filter(item => item.dictCode === row.cronJobFiled)
              const arr2 = this.currentTimeList.filter(item => item.dictCode === row.cronJobRule)
              return (<span>{arr2.length && arr2[0].dictName }{ arr1.length && arr1[0].dictName }{row.cronJobDay}</span>)
            }
          },
          {
            prop: 'mcenterCode',
            label: '消息中心模板编码',
            minWidth: '100'
          },
          {
            prop: 'contents',
            label: '消息内容',
            minWidth: '100'
          },
          {
            prop: 'enable',
            label: '启用状态',
            minWidth: '100',
            render: (creat, row) => {
              if (row.enable) {
                return <span>启用</span>
              } else {
                return <span>停用</span>
              }
            }
          }
        ],
        btnList: this.isProduction ? null : [
          {
            buttonName: '新增',
            optCode: 'add',
            outerFlag: true
          },
          {
            buttonName: '编辑',
            optCode: 'edit',
            outerFlag: true
          },
          {
            buttonName: '启用',
            optCode: 'enable',
            outerFlag: true
          },
          {
            buttonName: '停用',
            optCode: 'unable',
            outerFlag: true
          }]
      }
    }
  },
  async created() {
    await this.getDictByPatchTypeAll(['SHOP_SURVEY_STATE', 'PIC_DESIGN_SCHEDULE',
      'SHOP_DECORATION_STEPS', 'SHOP_DESIGN_STATE', 'DESIGN_TASK_STATE',
      'REMIND_TYPE', 'REMIND_ROLE', 'CRON_JOB_FILED', 'CRON_JOB_RULE', 'BEFORE_CONST_SCHEDULE', 'ACC_SCHEDULE']).then(res => {
      this.surveyStateList = res.SHOP_SURVEY_STATE // 测绘进度
      this.designScheduleList = res.PIC_DESIGN_SCHEDULE // 图纸设计进度
      this.decorationStepsList = res.SHOP_DECORATION_STEPS // 装修步骤
      this.designStateList = res.SHOP_DESIGN_STATE // 设计进度--设计流程
      this.taskStateList = res.DESIGN_TASK_STATE // 设计任务进度--设计任务
      this.constScheduleList = res.BEFORE_CONST_SCHEDULE// 门店建设
      this.accScheduleList = res.ACC_SCHEDULE// 资源饰品
      this.reminderModeList = res.REMIND_TYPE // 提醒方式
      this.reminderRoleList = res.REMIND_ROLE // 提醒角色
      this.performTasksList = res.CRON_JOB_FILED // 定时规则
      this.currentTimeList = res.CRON_JOB_RULE // 当前时间
    })
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    handleSearch(data) {
      this.otherFilters = [...data.filtersRaw]
      this.$nextTick(() => {
        this.$refs.newsFeeds.initTableData()
      })
    },
    clearSearch() {},
    // 选中行
    selectionChangeHandle(rows) {
      this.tableSelected = rows
    },
    // 按钮组
    btnOperate(flag) {
      switch (flag) {
        case 'add':
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', false)) {
            return
          }
          this.handleEdit(this.tableSelected)
          break
        // case 'del':
        //   this.handleDel(this.tableSelected)
        //   break
        case 'enable':
          this.handleChangeStatus(1)
          break
        case 'unable':
          this.handleChangeStatus(0)
          break
        // case 'export':// 导出
        //   this.exportVisible = true
        //   break
        // case 'import':// 导入
        //   this.importVisible = true
        //   break
        default:
          break
      }
    },
    // 新增/编辑
    handleEdit(data) {
      this.activatedData = {}
      if (data) {
        if (data.length > 1) {
          this.$message.warning('该操作仅支持单选')
          return
        }
        this.activatedData = data[0]
      }
      this.showAddPage = true
    },
    // 启用:1/停用:0  state停启用状态
    handleChangeStatus(state) {
      if (!this.tableSelected.length) {
        this.$message.warning(`请选择【${state ? '启用' : '停用'}】项`)
        return
      }
      const tmpArr = this.tableSelected.filter(row => row.enable === state)
      if (tmpArr.length > 0) {
        this.$message.warning(`当前所选分类包含${state ? '启用' : '停用'}状态，请勿重复操作`)
        return
      }
      this.$confirm(`此操作将当前所选数据${state ? '启用' : '停用'},是否继续`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableSelected.forEach(item => {
          item.enable = state
        })
        changeMessageState(this.tableSelected).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '操作成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      })
    },
    refreshTable(isInit) {
      this.$refs.newsFeeds.initTableData(isInit ? '' : 'onPage')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
